package com.vip.buycart.action;


import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.vip.buycart.bl.ProductBL;
import com.vip.buycart.bl.ProductManager;
import com.vip.buycart.entity.Product;
import com.vip.buycart.exception.RecordNotFoundException;
import com.vip.framework.exception.AppException;
import com.vip.framework.generic.BaseDispatchAction;
/**
 * 商品控制器类
 * @author mavi
 *
 */
public class ProductAction extends BaseDispatchAction {
    
    /**
     *  显示商品详情
     *  根据请求参数中的id查询数据库的得到相应资源，并在页面上显示。
     * @param mapping
     * @param form
     * @param request id：商品的id值。
     * @param response
     * @return 
     */
    public ActionForward show(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response){
        try{
            String idStr=request.getParameter("id");
            Long id=Long.valueOf(idStr); 
            ProductManager pm =(ProductManager)this.getBean("productBl");
            Product product=pm.getProductById(id);
            
            request.setAttribute("product", product);
            return mapping.findForward("success");
            
        }catch(NumberFormatException e){
            log.info("非法请求参数id:不是数字!");
            this.setErrorMessage(request, "product.param.not.valid");
            return mapping.findForward("error");
            
        }catch(RecordNotFoundException e){
            log.info("商品查询异常,id对应得资源未找到！id:"+((Long[])e.getMessageArgs())[0]);
            this.setErrorMessage(request, "product.not.found");
            return mapping.findForward("error");
        }
    }
    /**
     * 比较商品 
     *  选中2~3个商品
     * @param mapping
     * @param form
     * @param request 
     * @param response
     * @return
     */
    public ActionForward compare(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response){
        try{
            log.debug(" action compare");
            //获取id
            DynaActionForm daf=(DynaActionForm)form;
            String[] productIds=(String[])daf.get("productIds");
            if(null!=productIds&&productIds.length>3){
                throw new AppException();
            }
            Long[] ids=new Long[productIds.length];
            for (int i = 0; i < productIds.length; i++) {
                ids[i]=Long.valueOf(productIds[i]);
            }
            ProductManager pm =(ProductManager)this.getBean("productBl");
            List<Product> products=pm.getProductByIds(ids);
            //TODO 离开相关页面后清除Session
            request.getSession().setAttribute("productsInCompareBox", products);
            //request.setAttribute("products", products);
            return mapping.findForward("success");
            
        }catch(NumberFormatException e){
            log.info("非法请求参数id:不是数字!");
            this.setErrorMessage(request, "product.param.not.valid");
            return mapping.findForward("error");
            
        }catch(RecordNotFoundException e){
            log.info("商品查询异常,id对应得资源未找到！ids:"+(Long[])e.getMessageArgs());
            this.setErrorMessage(request, "product.not.found");
            return mapping.findForward("error");
            
        } catch (AppException e) {
            log.info("请求参数异常，id个数超过3个。");
            this.setErrorMessage(request, "product.param.not.valid");
            return mapping.findForward("error");
        }
    }
	/**
	 * 分页查询出商品信息,以图片为主的形式分页把商品显示出来.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward showImage(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		{ 	
			//每页显示行
			int row = 9;
			
			//得到商品类别的ID
			String productCategoryId = request.getParameter("productCategoryId");
			//得到商品类别的名字
			String productCategoryName = request.getParameter("productCategoryName");
			//得到当前页码.
			String currentPageStr = request.getParameter("currentPage");
			//总条数
			Long id = -1l;
			int currentPage=1;
			try {
				request.setCharacterEncoding("gb2312");
				productCategoryName=	new String(productCategoryName.getBytes("ISO-8859-1"),"gb2312");
				id = Long.valueOf(productCategoryId);
				
			}catch (NumberFormatException e) {
				 log.info("请求参数不正确,商品类型ID:"+productCategoryId);
		         this.setErrorMessage(request, "product.param.notnumber");
		         return mapping.findForward("error");
			} catch (UnsupportedEncodingException e) {
				 log.info("不支持的字符集.");
		         this.setErrorMessage(request, "product.UnsupportedEncoding");
		         return mapping.findForward("error");
				
			}	
			try
			{
				if(currentPageStr!=null)
				{
					currentPage = java.lang.Integer.parseInt(currentPageStr);
				}
			}catch (NumberFormatException e) {
				 log.info("请求参数不正确,当前页码:"+currentPageStr);
		         this.setErrorMessage(request, "product.param.notnumber");
		         return mapping.findForward("error");
			}
			//得到BL类.
			ProductBL dao =(ProductBL)getBean("productBL");
			//得到总条数,计算出总页数
			int totalPage = dao.getProductImageCount(id);		
			if(totalPage%row!=0)
			{
				totalPage = totalPage/row+1;
			}
			else
			{
				totalPage = totalPage/row;
			}
			//如果请求诉页码大于,总页码则跳出错误页面中
			if(currentPage >totalPage)
			{
				return mapping.findForward("error");
			}
			
			//得到当前页数据
			List<Product> products = dao.getProductImage(id, currentPage, row);
			//把当前页,总页数,当前页数据,商品类别Name,商品类别ID 信息传入显示的jsp中
			request.setAttribute("currentPage", currentPage);
			request.setAttribute("totalPage", totalPage);
			request.setAttribute("products", products);
			request.setAttribute("productCategoryName", productCategoryName);
			request.setAttribute("productCategoryId", productCategoryId);
			//跳到显示jsp中
			return mapping.findForward("success");
		}
	}
}
